package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping(value = "/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        //TODO   1.接口防刷   未完成
        //从redis上获取 key sms:code:phone 的对应的值
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
       //判断是否为空 redisCode
         if(!StringUtils.isEmpty(redisCode)) {
             //如果不为空获取 123456_System.currentTimeMillis()【当时存储redis的时间以毫秒秒为单位】
             // 截取时间
            long l = Long.parseLong(redisCode.split("_")[1]);
            //获取当前的时间减去redis缓存的时间看是否小于60000
             //1秒=1000毫秒
            if (System.currentTimeMillis() - l < 60000) {
                //如果小于,则报出异常
                //60秒内不能在发短信
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
         //程序到这里代码 ，第一次获取验证码或者是已经过了60秒
           //随机获取新的验证码
        String code = UUID.randomUUID().toString().substring(0, 5);
         //把验证码封装成redis需要的状态   123456_当前时间
        String s = code + "_" + System.currentTimeMillis();
       //往reids中存储指定格式的数据   key sms:code:phone  value  123456_当前时间
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone,s);

        //调用远程方法发送短信   gulimall-third-party
        thirdPartFeignService.sendCode(phone,code);
        return R.ok();
    }

    /*
    * TODO 重定向携带数据,利用session原理，将数据放在session中
    * */
    @PostMapping(value = "/register")
    public String register(@Valid UserRegisterVo vos, BindingResult result,
                           RedirectAttributes attributes) {
   //@Valid 用于验证JSR303 如果有错误返回到  BindingResult
        //result.hasErrors() 判断有没有异常 如果有返回 true 否则 false
     if (result.hasErrors()) {
         //获取getFieldErrors  FieldError::getField(获取错误id)  FieldError::getDefaultMessage()
         Map<String, String> errors = result.getFieldErrors()
                 .stream()
                 .collect(Collectors.toMap(
                         FieldError::getField,
                         FieldError::getDefaultMessage));
         attributes.addAttribute("errors", errors);
         //效验出错回到注册页面
         return "redirect:http://auth.gulimall.com/reg.html";
     }

        //校验验证码
        String code = vos.getCode();
       //从redis中获取校验码  sms:code:phone
        String redisCode  = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
        //判断校验码是否为空
        if (!StringUtils.isEmpty(redisCode)){
              //判断redis和验证码和传过来的验证码是不是同一个
                if (redisCode.split("_")[0].equals(code)){
                      //删除验证码，令牌机制
                    redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vos.getPhone());
                   //验证码通过，进行真正的注册
                    R register = memberFeignService.register(vos);
                    if (register.getCode()==0){
                        //成功
                        return "redirect:http://auth.gulimall.com/login.html";
                    }else {
                        //失败
                        Map<String, String> errors = new HashMap<>();
                        errors.put("msg", register.getData("msg",new TypeReference<String>(){}));
                        attributes.addFlashAttribute("errors",errors);
                        return "redirect:http://auth.gulimall.com/reg.html";
                    }

                }else {
                    //效验出错回到注册页面
                    Map<String, String> errors = new HashMap<>();
                    errors.put("code","验证码错误");
                    attributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            } else {
            //效验出错回到注册页面
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

    }

    @PostMapping(value = "/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session) {

        R login = memberFeignService.login(vo);
        if (login.getCode()==0){
            return "redirect:http://gulimall.com";
        }else {
            HashMap<String, Object> errors= new HashMap<>();
           errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            errors.put("errors",errors);
            attributes.addAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }


}
